﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WEBRM.Dominio.Repositorios;
using WEBRM.Dominio.Entidades;
using WEBRM.Repositorio.Helpers;
using NHibernate;
using NHibernate.Linq;


namespace WEBRM.Repositorio.Repositorios
{
    public class BaseRepositorio<T> : IRepositorio<T> where T : IEntidade
    {
        public T Obter(long id)
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.Get<T>(id);
        }

        public IList<T> ObterTodos()
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return (from t in session.Linq<T>()
                        select t).ToList();
        }

        public T Salvar(T entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(entity);
                    transaction.Commit();
                }
            }
            return entity;
        }

        public void Excluir(T entity)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.Delete(entity);
                    transaction.Commit();
                }
            }
        }
    }
}
